package com.honghu.cloud.tools;

import javax.servlet.http.HttpServletRequest;

import com.honghu.cloud.constant.Globals;
import com.honghu.cloud.dto.UserDto;
import com.honghu.cloud.feign.UserFeignClient;
import com.honghu.cloud.redis.RedisUtil;
import com.honghu.cloud.spring.SpringContextHolder;

/**
 * 根据当前登录用户信息
 * @author Administrator
 *
 */
public class SecurityUserHolder {
	
	/**
	 * 获取当前用户对象
	 * @param request
	 * @return
	 */
	public static UserDto getCurrentUser(HttpServletRequest request) {
		// 从request中取出当前用户id
		Object login_user_id = request.getAttribute("login_user_id");
		Long user_id = null2Long(login_user_id);
		
		if(null == user_id){
			 return null;
		}
		
		RedisUtil redisUtil =  SpringContextHolder.getBean(RedisUtil.class);
		UserFeignClient userService =  SpringContextHolder.getBean(UserFeignClient.class);
		
		// 从redis取出用户信息，不存在查询用户信息存到redis中
		UserDto userDto = (UserDto) redisUtil.get(Globals.USER_INFO_MARK + user_id);
		if (userDto == null) {
			userDto = userService.selectByPrimaryKey(user_id);
			if(userDto != null){
				redisUtil.set(Globals.USER_INFO_MARK + user_id, userDto, Globals.USER_INFO_EXPIRE_TIME);
			}
		}
		
		return userDto;
	}
	
	/**
	 * 获取当前用户id
	 * @param request
	 * @return
	 */
	public static Long getCurrentUserId(HttpServletRequest request) {
		// 从request中取出当前用户id
		Object login_user_id = request.getAttribute("login_user_id");
		Long user_id = null2Long(login_user_id);
		
		return user_id;
	}
	
	public static Long null2Long(Object s) {
		Long v = null;
		if (s != null) {
			try {
				v = Long.parseLong(s+"");
			} catch (Exception localException) {
			}
		}
		return v;
	}
}
